package lesson31;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

public class MyMethodHandle {

    public static void main(String[] args) throws Throwable {
        System.out.println(new MyMethodHandle().sound(new Bike()));
        System.out.println(new MyMethodHandle().sound(new Animal()));
        System.out.println(new MyMethodHandle().sound(new Man()));
    }

    String sound(Object o) throws Throwable {
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        MethodType methodType = MethodType.methodType(String.class);
        MethodHandle methodHandle = lookup.findVirtual(o.getClass(), "sound", methodType);
        return (String) methodHandle.invoke(o);
    }

    static class Bike{
        String sound(){
            return "ding ding";
        }
    }

    static class Animal{
        String sound() {
            return "wow wow";
        }
    }

    static class Man extends Animal{
        @Override
        String sound() {
            return "hou hou";
        }
    }
}
